import { baseUrl as BASE_URL, timeout as TIMEOUT} from '../api/config'

export interface RequestConfig {
  url:string,
  method:HttpRequestMethod,
  data?:any,
  header?:HttpRequestHeader
  contentType?:string,
  token?:boolean
}

interface HttpRequestHeader{
  Authorization?:string,
  // 'content-type': 'application/json' // 默认值
  'content-type'?:string
}

interface WxHttpResponse{
  code:number,
  msg:string,
  data:any
}

export interface LengyuHttpResponse{
  code:number,
  msg:string,
  data:any
}
export const LENGYU_SUCCESS_CODE:number=20000;

export enum HttpRequestMethod {
	GET = "GET",
	POST = "POST",
};

export interface PageRequestParam{
  pageIndex:number;
  pageSize:number;
  paramMapObj?:JSON;
}


// let httpMethod = getHttpMethod("get"); // 正确
// httpMethod = getHttpMethod("customMethod".toLowerCase()); 

/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function request(body:RequestConfig):Promise<LengyuHttpResponse>{
  let url = BASE_URL + body.url;
  let data = body.data;
  let method = body.method;
  let emptyHeader:HttpRequestHeader ={}
  let header = body.header ? body.header : emptyHeader;
    wx.showLoading({
        title: "加载中",
        mask: true  //开启蒙版遮罩
    });
    if(body.token){
      header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
    }
    if(body.contentType){
      header['content-type'] = body.contentType;
    }

  
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.request({
            url: url,
            timeout: TIMEOUT,
            method: method,
            data: data,
            header: header,
            success: (res) => {
                // if (res.data && res.data.code == 401) {
                //     // 跳转登录
                //     reject(res.data);
                //     wx.navigateTo({
                //       url: '/pages/login/login',
                //     })
                // }
                //微信的回调出发Promise的回调

                if(res.statusCode == 200){
                  wx.hideLoading()
                  resolve(res.data as LengyuHttpResponse);
                }
                else{
                  let res1:LengyuHttpResponse = {
                    code:res.statusCode,
                    data:"",
                    msg:res.data.error
                  }
                  resolve(res1)
                }
              
            },
            fail: (res) => {
                wx.hideLoading()
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
        
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            }
        })
    })
}


/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function download(body:RequestConfig):Promise<WechatMiniprogram.DownloadFileSuccessCallbackResult>{
  let url =  body.url;
    wx.showLoading({
        title: "文件下载中",
        mask: true  //开启蒙版遮罩
    });
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.downloadFile({
            url: url,
            timeout: TIMEOUT,
            success: (res) => {
                //微信的回调出发Promise的回调
                // resolve(res.data as LengyuHttpResponse);
                 // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  resolve(res)
                }
            },
            fail: (res) => {
                wx.hideLoading()
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            }
        })
    })
}



/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function upload(body:RequestConfig,filePath:string
                        ):Promise<LengyuHttpResponse>{
    let url = BASE_URL + body.url;
    wx.showLoading({
        title: "文件上传中",
        mask: true  //开启蒙版遮罩
    });
    let emptyHeader:HttpRequestHeader ={}
    let header = body.header ? body.header : emptyHeader;
    if(body.token){
      header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
    }
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.uploadFile({
            url: url,
            timeout: TIMEOUT,
            filePath: filePath,
            name: 'file',
            header: header,
            formData: body.data,
            success: (res) => {
                //微信的回调出发Promise的回调
                // resolve(res.data as LengyuHttpResponse);
                 // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  const result: LengyuHttpResponse = <LengyuHttpResponse>JSON.parse(res.data);
                  resolve(result);
                }
            },
            fail: (res) => {
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            }
        })
    })
}


/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function uploadBigFile(body: RequestConfig,
   filePath: string,size:number
): Promise<LengyuHttpResponse> {
  // 设置每片的大小（例如，每次读取20MB）
  let chunkSize = 1024*1024*2;
  // wx.showLoading({
  //   title: "加载中",
  //   mask: true  //开启蒙版遮罩
  // });
  
  //返回Promise对象
  return new Promise(async (resolve, reject) => {
    // 创建一个文件上传器实例
    let count =Math.ceil(size/chunkSize);
    let fileName = new Date().getTime()+".txt";
    wx.showLoading({
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });

    for(let i=0;i<count;i++){
      console.log("第"+i+"次读取文件")
      let progress = (i+1)/count
      console.log("保存上传进度"+progress)
      wx.setStorageSync("upload_progress",progress)
      let chunkData = await readChunkFile(filePath,size,chunkSize*i,chunkSize);
      // 将二进制数据转换为 Base64 编码
      body.data=chunkData
      await uploadStream(body,i,count,fileName);
    }
    wx.hideLoading();
  })
}
function uploadStream(body: RequestConfig,index:number,totalIndex:number,fileName:string): Promise<LengyuHttpResponse> {
  //返回Promise对象
  let url = BASE_URL + body.url + "?index="+index+"&totalIndex="+totalIndex+"&fileName=" + fileName;
  let data = body.data;
  let method = body.method;
  let emptyHeader:HttpRequestHeader ={}
  let header = body.header ? body.header : emptyHeader;
    
    if(body.token){
      header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
    }
    if(body.contentType){
      header['content-type'] = "application/octet-stream";
    }
  return new Promise((resolve, reject)=> {
    wx.request({
        url: url,
        timeout: 300000,
        method: method,
        data: data,
        header: header,
        success: (res) => {
            // if (res.data && res.data.code == 401) {
            //     // 跳转登录
            //     reject(res.data);
            //     wx.navigateTo({
            //       url: '/pages/login/login',
            //     })
            // }
            //微信的回调出发Promise的回调
            resolve(res.data as LengyuHttpResponse);
        },
        fail: (res) => {
            wx.showToast({
                title: res.errMsg,
                icon: 'error',
                duration: 2000
            })
            reject(res);
        },
        complete: () => {
           
        }
    })
})
}

export function readChunkFile(
  filePath: string,fileSize:number,offset:number,chunkSize:number
): Promise<any>{
  return new Promise((resolve, reject) => {
    const fs = wx.getFileSystemManager();
    let fileContent = []
    if (offset >= fileSize) {
      // 所有内容都已读取完毕
      // console.log('File read complete:', fileContent);
      reject("File read complete")
    }
    const end = Math.min(offset + chunkSize, fileSize);
    console.log("end:" + end+"offset:"+offset)
    console.log("fileSize:" + fileSize+"chunkSize:"+chunkSize)
    fs.readFile({
      filePath: filePath,
      encoding: 'utf8',
      position: offset,
      length: end - offset,
      success: (result) => {
        // console.log(result.data); // 或将结果推入数组
        offset = end;
        resolve(result.data);
      },
      fail: (err) => {
        console.error('Failed to read file chunk:', err);
        reject(err)
      },
    });
  })
  
}